<?php

require "config/dbconfig.php";

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

class _mysqli_result {
  protected $m_stmt, $results;
  
  public function __construct( $stmt ) {
    $this->m_stmt = $stmt;
  
    $this->results = range(0, $stmt->field_count-1);
    $ref_array = array();
    foreach($this->results AS $I => $result) $ref_array[$I] = &$this->results[$I];
    call_user_func_array( array($stmt, 'bind_result'), $ref_array);
  }
  
  public function fetch_next() {
    return $this->m_stmt->fetch();
  }
  
  public function get_row() {
    return $this->results;
  }
  
  public function close() {
    $this->m_stmt->close();
  }
}

function mysql_qp($query, $values = array(), $types = "") {
  global $mysqli;
  
  $stmt = $mysqli->prepare($query);

  if (count($values) > 0 ) {
    $gentypes = strlen($types) == 0; // if not set generate it...
    
    foreach($values AS $I => $value) {
      $values[$I] = &$value;
      if ($gentypes) {
        if (is_string($value)) $types .= "s";
        else if (is_int($value)) $types .= "i";
        else if (is_float($value)) $types .= "d";
        else {
          trigger_error("mysql_qp: Could not detect type of parameter $I for parameter binding.", E_USER_ERROR);
          return;
        }
      }
    }
    call_user_func_array( array($stmt, 'bind_param'), array_merge(array($types), $values) );
  }
  
  $stmt->execute();
  
  return new _mysqli_result($stmt);
}

function mysql_qps($query, $values = array(), $types = "") {
  $res = mysql_qp($query, $values, $types);
  $res->fetch_next();
  $result = $res->get_row();
  $res->close();
  return $result;
}  

?>
